package www.baidu.ofo_bike.user.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import www.baidu.ofo_bike.cache.CommonCacheUtils;
import www.baidu.ofo_bike.common.exception.MaMaBikeException;
import www.baidu.ofo_bike.security.AESUtil;
import www.baidu.ofo_bike.security.Base64Util;
import www.baidu.ofo_bike.security.MD5Util;
import www.baidu.ofo_bike.security.RSAUtil;
import www.baidu.ofo_bike.user.dao.UserMapper;
import www.baidu.ofo_bike.user.entity.User;

@Slf4j
@Service("userServiceImpl")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private  CommonCacheUtils commonCacheUtils;

    @Override
    public String login(String data, String key) throws MaMaBikeException {
        String token=null;
        String decryptdata=null;
        /*解密密钥及解密加密数据*/
        try {
            byte[] dekey=RSAUtil.decryptByPrivateKey(Base64Util.decode(key));

            decryptdata=AESUtil.decrypt(data,new String(dekey,"utf-8"));
            if(decryptdata==null){
                throw new Exception();
            }
            /*获取解密数据后的电话及验证码*/
            JSONObject jsonObject =JSON.parseObject(decryptdata);
            String mobile=jsonObject.getString("mobile");
            String code=jsonObject.getString("code");
            if (StringUtils.isBlank(mobile)||StringUtils.isBlank(code)){
                throw new Exception();
            }
            /*去redis取验证码手机号码，验证是否一致，匹配说明是本人手机，继续下部操作*/
            String enCode= commonCacheUtils.getValue(mobile);
            User user;
            if (code.equals(enCode)){
                user= userMapper.selectByMobile(mobile);
                if (user==null){
                    user=new User();
                    user.setMobile(mobile);
                    user.setNackname(mobile);
                    userMapper.insertSelective(user);
                }
            }else {
                throw  new MaMaBikeException("验证码不匹配");
            }


            /*验证通过后，生成token，如果不存在生成token存入redis*/
            try {
                token=generator(user);
            } catch (Exception e) {
                throw  new MaMaBikeException("生成token失败");
            }


        } catch (Exception e) {
            log.error("Fail to Login",e);
            throw new MaMaBikeException("数据异常");
        }
        return null;
    }

    private String generator(User user) {
        String source=user.getId()+""+user.getMobile()+""+System.currentTimeMillis();
        return MD5Util.getMD5(source);
    }
}
